<?php

namespace app\store\controller\integral;


use app\store\controller\BaseController;
use app\store\model\IntegralInterval;
use app\store\service\IntegralIntervalService;
use think\exception\ValidateException;
use think\facade\View;

class IntervalController extends BaseController
{

    /**
     * 积分区间列表
     * */
    public function index()
    {
        $integralCategoryService = new IntegralIntervalService();
        $list = $integralCategoryService->getIntegralIntervalList();

        return View::fetch('',['list' => $list]);
    }

    /**
     * 添加积分区间
     * */
    public function create()
    {
        View::engine()->layout(false);

        return View::fetch();
    }

    /**
     * 编辑积分区间
     * */
    public function edit()
    {   
        $id = $this->request->get('id/d');

        $integralIntervalService = new IntegralIntervalService();
        $row = $integralIntervalService->findIntegralInterval($id);

        View::engine()->layout(false);

        return View::fetch('',['row' => $row]);
    }

    /**
     * 保存积分区间
     *
     * */
    public function save()
    {
        $param = $this->request->post();
        
        try{
            validate('IntegralIntervalValidate')->check($param);
        }catch (ValidateException $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        $param['store_id'] = session('store_id');

        $model =  IntegralInterval::create($param);

        return !empty($model['id']) ? json(['code' => 1, 'msg' => '保存成功!']) : json(['code' => 0, 'msg' => '保存失败!']);
        
    }

    public function switch()
    {
        $param = $this->request->post();

        try {
            validate('IntegralIntervalValidate.switch')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        IntegralInterval::update($param);

        return json(['code' => 1, 'msg' => '更新成功!']);
    }

    public function update()
    {
        $param = $this->request->post();
        
        try{
            validate('IntegralIntervalValidate.edit')->check($param);
        }catch (ValidateException $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        $model =  IntegralInterval::update($param);

        return !empty($model['id']) ? json(['code' => 1, 'msg' => '更新成功!']) : json(['code' => 0, 'msg' => '更新失败!']);
    }


    public function delete()
    {
        $id = $this->request->get('id/d');

        $res = IntegralInterval::destroy($id);

        return  $res ? json(['code' => 1,'msg' => '删除成功!']) : json(['code' => 0, 'msg' => '删除失败']);

    }
}